#!/user/bin/python
#coding = utf-8
import shutil
import os
import json
import sys

def getParamString(name,default=''):
	value = os.getenv(name)
	if value == None:
		value = default	
	return value

def getParamInt(name,default=0):
	value = os.getenv(name)
	if value == None:
		value = default
	else:
		value = int(value)	
	return value

def getParamBool(name,default=False):
	value = os.getenv(name)
	if value == None:
		value = default
	elif value == 'true':
		value = True
	else:
		value = False	
	return value

def createOutputFolder(path):
    if os.path.exists(path):
        shutil.rmtree(path)	
    os.mkdir(path)
	
def main():
    print('Get parameters from Jenkins.')
    JOB_NAME = getParamString('JOB_NAME')
    BUILD_NUMBER = getParamString('BUILD_NUMBER')
    WORKSPACE = getParamString('D:/project_unity/Jenkins')
    BUILD_TYPE = getParamString('BUILD_TYPE')
    VERSION_NO_BASE = getParamString('VERSION_NO_BASE')
    SVN_VERSION_NO = getParamInt('SVN_VERSION_NO')
    VERSION_TYPE = getParamString('VERSION_TYPE')
    BUILD_TIMESTAMP = getParamString('BUILD_TIMESTAMP')
    DEBUG_MODE = getParamBool('DEBUG_MODE', False)
    APP_NAME = getParamString('APP_NAME', 'App')
    BUILD_SCENES = getParamString('BUILD_SCENES').split('\n')
    PACKAGE_SHARED_FOLDER = getParamString('PACKAGE_SHARED_FOLDER')
    unity = f'C:/Program Files/Unity/Hub/Editor/2022.3.44f1c1/Editor/Unity.exe'
    print(f'Unity path: {unity}')
	
    output_folder = f'C:/Project/builds_{JOB_NAME}'    
    log_path = f'{output_folder}/{JOB_NAME}_build_log_{BUILD_NUMBER}'            
    
    createOutputFolder(output_folder)
	
    json_path = f'{output_folder}/buildConfig.json'
    print(f'Creating config json to {json_path}')

    build_config = {}
    if BUILD_TYPE == 'PC':
            build_config['OS'] = 0
    elif BUILD_TYPE == 'Android':
            build_config['OS'] = 3
    build_config['Store'] = 0    
    build_config['VersionBase'] = VERSION_NO_BASE
    build_config['SvnReversion'] = SVN_VERSION_NO
    build_config['CleanAssetsCache'] = True
    build_config['VersionType'] = VERSION_TYPE
    build_config['BuildDateTime'] = BUILD_TIMESTAMP
    build_config['OutputFolder'] = output_folder
    build_config['DevelopmentMode'] = DEBUG_MODE
    build_config['AppName'] = APP_NAME
    build_config['BuildScenes'] = BUILD_SCENES

    with open(json_path, 'w', encoding='utf-8') as file_obj:
            json.dump(build_config, file_obj, indent=4, ensure_ascii=False)
			
    print('Start Unity building, please wait...')
    sys.stdout.flush()
    proj_path = WORKSPACE
    log_path_1 = f'{log_path}_1.txt'
    exe_result = os.system(f'"{unity}" -batchmode -nographics -executeMethod BuilderCommandline.Build_SwitchEnv -projectPath {proj_path} -logFile {log_path_1} -configFilePath:{json_path}')	
    if exe_result != 0:
        print(f'call Unity Build_SwitchEnv failed. result={exe_result}')	
        exit(1)

    log_path_2 = f'{log_path}_2.txt'
    exe_result = os.system(f'"{unity}" -batchmode -quit -nographics -executeMethod BuilderCommandline.Build_MakePackage -projectPath {proj_path} -logFile {log_path_2} -configFilePath:{json_path}')	
    if exe_result != 0:
        print(f'call Unity Build_MakePackage failed. result={exe_result}')	
        exit(1)

    print("Build Successful!")

    
if __name__ == '__main__':
    main()
	
